﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Business.EntityFrameworkCore;
using mozhi.smarterp.Business.Enums;
using mozhi.smarterp.Business.Purchases;
using mozhi.smarterp.Business.Purchases.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Business.Repositories
{
    public class PurchaseRequisitionRepository : DocumentEfCoreRepository<BusinessDbContext, PurchaseRequisition, Guid>, IPurchaseRequisitionRepository
    {
        public PurchaseRequisitionRepository(IDbContextProvider<BusinessDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<long> GetCountAsync(string number, DateTime? startDate, DateTime? endDate, DocumentStatusType status, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<PurchaseRequisition>().AsNoTracking()
                .WhereIf(!number.IsNullOrEmpty(), x => x.Number.Contains(number))
                .WhereIf(startDate.HasValue, x => x.Date >= startDate)
                .WhereIf(endDate.HasValue, x => x.Date <= endDate)
                .WhereIf(status != default, x => x.Status == status)
                .CountAsync(cancellationToken);
            return count;
        }

        public async Task<List<PurchaseRequisition>> GetPagedListAsync(string number, DateTime? startDate, DateTime? endDate, DocumentStatusType status, int skipCount, int maxResultCount, string sorting, bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            var query = (!includeDetails) ? await GetDbSetAsync() : await WithDetailsAsync();
            return await query
                .WhereIf(!number.IsNullOrEmpty(), x => x.Number.Contains(number))
                .WhereIf(startDate.HasValue, x => x.Date >= startDate)
                .WhereIf(endDate.HasValue, x => x.Date <= endDate)
                .WhereIf(status != default, x => x.Status == status)
                .OrderByIf<PurchaseRequisition, IQueryable<PurchaseRequisition>>(!sorting.IsNullOrWhiteSpace(), sorting)
                .PageBy(skipCount, maxResultCount)
                .ToListAsync(GetCancellationToken(cancellationToken));
        }
    }
}
